<template>
  <view class=" page">
    <view v-if="equips.length !== 0">
      <o-grid col="2" gutter="true" square="false" border="false" radius="true">
        <o-grid-item v-for="(item, index) in equips" :index="index" :key="index" @tap="select(index)"
                     @longpress="toEdit">
          <view class="equipment-item" style="text-align: left;">
            <view class="wrap">
              <view class="top">
                <image class="pic" src="@/static/images/51276e00a4890f11936fcc00b81e6367.png"/>
                <uni-icons color="#77c7e5" type="checkbox-filled"
                           v-if="selectedIndexs.indexOf(index) !== -1 && editMode"/>
                <uni-icons color="gray" type="checkbox-filled" v-else-if="editMode"/>
              </view>
              <text class="name_equip">{{ item.name_equip }}</text>
              <view>
                <text class="detail">{{ item.name_room + " | " }}</text>
                <text class="detail" :style="{
				                            color:
				                                item.workingtag_equip === '未连接'
				                                ? '#a6a6a6'
				                                : item.workingtag_equip === '已连接'
				                                ? '#03ac79'
				                                : item.workingtag_equip === '运行中'
				                                ? '#03ac79'
				                                : item.workingtag_equip === '待机'
				                                ? '#03ac79'
				                                : item.workingtag_equip === '设备离线'
				                                ? '#ff0000'
				                                : item.workingtag_equip === '任务结束'
				                                ? '#ff0000'
				                                : item.workingtag_equip === '运行暂停'
				                                ? '#ff0000'
				                                : '',
				                          }">{{ item.workingtag_equip }}
                </text>
              </view>
            </view>
          </view>
        </o-grid-item>
      </o-grid>
    </view>

    <view class="typelist" :class="{'typelist-active':editMode}">
      <view class="tabWrap">
        <view class="tab-item" v-for="(item, index) in typeList" :key="index"
              v-if="index==0||selectedIndexs.length<2&&index>0"
              :class="{ active: selectedIndexs.indexOf(index) != -1 }" @click="clickTable(index)">
          <view :class="[tabCurrentIndex == index ?'active':'']">
            <image :src="item.srcUrl" style="width: 50rpx;height: 50rpx;"/>
          </view>
          <text style="color: #696b66;font-size: 28rpx;">{{ item.name }}</text>
        </view>
        <view class="tab-item">
          <view :class="[tabCurrentIndex == -1 ?'active':'']" style="height: 58rpx">
            <uni-icons type="checkmarkempty" style="font-size: 50rpx;"
                       @click="clickTable(-1)"></uni-icons>
          </view>
          <text style="color: #696b66;font-size: 28rpx;">完成</text>
        </view>
      </view>
    </view>

    <!-- 删除设备 -->
    <next-modal
        :show="isDeleteequip"
        @confirm="deleteequip"
        @cancel="isDeleteequip=false"
        :title="`注意`"
        content="是否删除该设备"
        confirmColor="#000"
        :autoClose="false"
    >
    </next-modal>
    <!-- 重命名 -->
    <next-modal
        :show="showReNameDialog"
        @confirm="changename"
        @cancel="showReNameDialog = false; inputClearValue=''; showClearIcon=false"
        :title="`重命名`"
        confirmColor="#000"
        :autoClose="false"
    >
      <view slot="content">
        <view class="modal-content">
          <input class="input" placeholder="请输入修改后的设备名称" :value="inputClearValue" @input="clearInput"/>
          <uni-icons type="clear" style="font-size: 40rpx;" v-if="showClearIcon" @click="clearIcon"/>
        </view>
      </view>
    </next-modal>

  </view>
</template>

<script>
import {
  mapState,
  mapMutations
} from 'vuex';
//获取用户绑定的设备列表(绑定加共享)
import {
  _getequiplistall
} from '@/service/equip.js'
import {
  _deleteequip
} from '@/service/equip.js'
// import { _moveroomequip } from '@/service/equip.js'
import {
  _moveequip
} from '@/service/equip.js'
import {
  _changename
} from '@/service/equip.js'
import {
  _sharingroomequip
} from '@/service/equip.js'
import {
  _getrooms
} from '@/service/room.js'
import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import NextModal from "@/uni_modules/next-modal/components/next-modal/next-modal.vue";

export default {
  components: {NextModal, UniIcons},
  data() {
    return {
      inputClearValue: '',
      equipname: '',
      nickname: '',
      account_user: '',
      password_user: '',
      rooms: [],
      equips: [],
      editMode: false,
      selectedIndexs: [], //当前选中的元素的索引
      // selectedIndex1: -1, //当前选中的元素的索引
      showShade1: false, //长按后设备右上角圈圈的显示状态  默认不显示
      tabCurrentIndex: '0',
      serialnum_sharingequip: '',
      account_sharingequip: '',
      serialnum_equip: '',
      serialnum_room: '',
      name_equip: '',
      showReNameDialog: false,
      showClearIcon: false,
      name: '',

      isDeleteequip: false,

      typeList: [{
        value: '1',
        srcUrl: '../../static/images/efff544c40d6ca31e3d98e9f42642b6d.png',
        selectSrcUrl: '../../static/images/efff544c40d6ca31e3d98e9f42642b6d.png',
        name: '删除',
        selected: false // 添加selected属性，默认为false
      },
        {
          value: '2',
          srcUrl: '../../static/images/7d9d29a6edb12017e2cdbf6da78f71fc.png',
          selectSrcUrl: '../../static/images/7d9d29a6edb12017e2cdbf6da78f71fc.png',
          name: '移动设备',
          selected: false // 添加selected属性，默认为false
        },
        {
          value: '3',
          srcUrl: '../../static/images/21b48f083461141fe0c21b7f8f5e8bd9.png',
          selectSrcUrl: '../../static/images/21b48f083461141fe0c21b7f8f5e8bd9.png',
          name: '重命名',
          selected: false // 添加selected属性，默认为false
        },
        {
          value: '4',
          srcUrl: '../../static/images/share (2).png',
          selectSrcUrl: '../../static/images/7fb848bc7cf281d60011673c809a0647.png',
          name: '共享',
          selected: false // 添加selected属性，默认为false
        }
      ],
    };
  },

  onLoad() {
    // 页面显示是默认选中第一个
    this.tabCurrentIndex = 0;
  },

  onShow() {
    let newdata;
    try {
      const value = uni.getStorageSync('userInfo');
      if (value != null) {
        this.nickname = value.nickname
        this.account_user = value.accountNum
        this.password_user = value.password
      }
    } catch (e) {
      console.error(e);
    }
    this.getequipsinfo();
  },
  methods: {
    navBack() {
      uni.navigateBack({})
    },
    toEdit() {
      this.selectedIndexs = [];//切换编辑状态初始化数组
      this.editMode = true;
    },
    async getequipsinfo() {
      let data = {
        account_user: this.account_user
      }
      let res = await _getequiplistall(data)
      this.equips = res.data
      // console.log(this.equips)
      for (let i = 0; i < this.equips.length; i++) {
        let s = this.equips[i].workingtag_equip;
        switch (s) {
          case 'DISCONNECT':
            this.equips[i].workingtag_equip = '设备离线';
            break;
          case 'CONNECTED':
            this.equips[i].workingtag_equip = '待机';
            break;
          case 'RUN':
            this.equips[i].workingtag_equip = '加热中';
            break;
          case 'ON':
            this.equips[i].workingtag_equip = '开机';
            break;
          case 'OFF':
            this.equips[i].workingtag_equip = '关机';
            break;
          case 'STOP':
            this.equips[i].workingtag_equip = '冷却中';
            break;
          case 'PULSE':
            this.equips[i].workingtag_equip = '保温中';
            break;
          default:
            // 处理未知状态，可以选择设置为原始状态或者其他默认值
            this.equips[i].workingtag_equip = s;
            break;
        }

      }
      console.log(this.equips)
    },

    select(index) {
      console.log("添加：", this.editMode);
      if (this.editMode) {
        console.log(index)
        let realIndex = this.selectedIndexs.indexOf(index);
        if (realIndex !== -1) {
          this.selectedIndexs.splice(realIndex, 1); //再次点击设备后selectedIndexs里面移除该设备
        } else {
          this.selectedIndexs.push(index); //当点击未选中的设备时，将添加对应设备的索引
        }
      }
      console.log('After toggle:', this.editMode, this.selectedIndexs); //打印切换后的值
    },

    clearIcon: function () {
      this.inputClearValue = '';
      this.showClearIcon = false;
    },
    clearInput: function (event) {

      this.inputClearValue = event.detail.value;
      console.log(event.detail.value.length)
      if (event.detail.value.length > 0) {
        this.showClearIcon = true;
      } else {
        this.showClearIcon = false;
      }
    },


    //删除设备
    async deleteequip() {
      if (this.selectedIndexs.length > 0) {
        console.log(this.serialnum_equip)
        console.log(this.account_user)
        let result = false;
        for (let index in this.selectedIndexs) {
          console.log(index)
          let realIndex = this.selectedIndexs[index];
          let temp = await _deleteequip({
            serialnum_equip: this.equips[realIndex].serialnum_equip,
            account_user: this.account_user
          });
          if ((result = temp.flag) == false) {
            break;
          } //删除设备异常就跳出
        }
        if (result) {
          this.isDeleteequip = false
          this.selectedIndexs = []; //设备删除成功后就清空数组
          uni.reLaunch({
            url: '/pages/allequips/allequips',
            success: () => {
              uni.navigateBack()
            }
          })
        } else {
          setTimeout(() => {
            uni.hideLoading();
            // this.$api.msg(data1.message);
            this.$api.msg("错误");
          }, 500);
        }
      } else {
        this.$api.msg('请先选择要进行操作的设备');
      }
    },
    //移动设备
    //跳转到moveroom
    toMoveRoom() {
      if (this.selectedIndexs.length != 0) {
        let serialnum_equip = this.equips[this.selectedIndexs[0]].serialnum_equip;
        // console.log(this.equips[this.selectedIndexs].serialnum_equip)
        uni.navigateTo({
          url: '/pages/moveroom/moveroom?serialnum_equip=' + serialnum_equip
        });
      } else {
        this.$api.msg('请先选择要进行操作的设备')
      }
    },
    //重命名
    async changename() {
      let equip = this.equips[this.selectedIndexs[0]];
      if (this.selectedIndexs.length != 0 && this.inputClearValue != '') {
        console.log(this.serialnum_equip)
        console.log(this.equipname)
        let data1 = {
          serialnum_equip: equip.serialnum_equip,
          name_equip: this.inputClearValue
        }
        let res = await _changename(data1);
        if (res.flag) {
          uni.hideLoading();
          this.showReNameDialog = false
          uni.reLaunch({
            url: '/pages/allequips/allequips',
            success: () => {
              uni.navigateBack()
            }
          })
        } else {
          setTimeout(() => {
            uni.hideLoading();
            this.$api.msg(data1.message);
          }, 500);
        }
      } else if (this.selectedIndexs.length == 0) {
        this.$api.msg('请先选择要进行操作的设备')
      } else if (this.inputClearValue == '') {
        this.$api.msg('设备名称不能为空')
      }
    },


    // 重命名
    reName() {
      if (this.selectedIndexs.length >= 1) {
        this.showReNameDialog = true;
      } else {
        this.$api.msg('请先选择要进行操作的设备')
      }
    },

    //跳转到sharingothers
    toShare() {
      if (this.selectedIndexs.length > 0) {
        let serialnum_equip = this.equips[this.selectedIndexs[0]].serialnum_equip;
        let name_equip = this.equips[this.selectedIndexs[0]].name_equip;
        console.log(serialnum_equip)
        uni.navigateTo({
          url: '/pages/sharingothers/sharingothers?serialnum_equip=' + serialnum_equip +
              '&name_equip=' + name_equip
        });
      } else {
        this.$api.msg('请先选择要进行操作的设备')
      }
    },
    //点击事件
    clickTable(index) {
      this.tabCurrentIndex = index;
      // console.log(this.tabCurrentIndex)
      if (this.tabCurrentIndex === 0) {
        this.isDeleteequip = true;
      } else if (this.tabCurrentIndex === 1) {
        this.toMoveRoom();
      } else if (this.tabCurrentIndex === 2) {
        this.reName();
      } else if (this.tabCurrentIndex === 3) {
        this.toShare();
      } else {
        this.editMode = false;
      }
    },
  }
};
</script>

<style scoped lang="scss">
.page {
  min-height: 100vh;
  background: #f7f7f7;
  //padding: 24rpx;
  box-sizing: border-box;
}

.typelist-active {
  bottom: 0 !important;;
}

.typelist {
  position: fixed;
  bottom: -160rpx;
  width: 100vw;
  height: 160rpx;
  display: flex;
  //align-items: center;
  transition: bottom 0.3s ease, opacity 0.3s ease;

  .tabWrap {
    height: 80rpx;
    width: 100%;
    display: flex;
    justify-content: space-around;
  }

  .tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;

    &.active {
      /* style for active tab */
    }
  }
}

.equipment-item {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  width: 100%;
  height: 250rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 24rpx 20rpx 20rpx 20rpx;
  box-sizing: border-box;

  .wrap {
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .top {
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 12rpx;

    .pic {
      width: 90rpx;
      height: 110rpx;
      object-fit: contain;
      margin-bottom: 0;
    }
  }

  .name_equip {
    font-size: 28rpx;
    font-weight: bold;
    color: #222;
    margin-bottom: 8rpx;
    //text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .detail {
    font-size: 22rpx;
    color: #999;
    //text-align: left;
  }
}

.modal-content {
  padding: 10rpx 24rpx;
  display: flex;
  justify-content: space-between;
  border-bottom: solid #DADADAFF;

  .content {
    color: #999;
  }

  .input {
    padding: 5px;
  }
}
</style>